package com.example.myapplication;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.util.Log;
import android.widget.TextView;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.nucypher.crypto.pkcrypto.eccEncryption;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;


public class MainActivity extends AppCompatActivity {


    private Button button;
    private Button button2;
    private TextView textView2;
    private TextView textView3;
    //private int i=0;//记录点击次数
    //指定加密算法为RSA
    private static final String ALGORITHM = "RSA";
    // 密钥长度，用来初始化 
    private static final int KEYSIZE = 1024;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        textView2 = (TextView) findViewById(R.id.textView2);
        textView3 = (TextView) findViewById(R.id.textView);

        //检查密钥文件是否已存在，若存在，button的text信息更新
        FileInputStream f = null;
        try {
            f = openFileInput("mykeys");
            button.setText("已初始化，请不要重复点击");
        } catch (FileNotFoundException e) {
            button.setText("未初始化。");
        }
        /*try {
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/


        //密钥生成状态
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //控制一次初始化
                if (button.getText().toString().contains("已初始化"))
                    return;
                //初始化
                button.setText("...");
                try {
                    //生成密钥保存在文件中
                    eccEncryption ec1 = new eccEncryption();
                    System.out.println(System.getProperty("user.dir"));
                    ec1.init("/data/data/com.example.myapplication/files/mykeys");

                    //将设备号和公钥以JSON格式发送给CM ，并存储CM的公钥；
                    EcRes ecRes=new EcRes();
                    ecRes.type="75";
                    //ecRes.publicKey=new String(ec1.getPublicKeyByte(),StandardCharsets.UTF_8);
                    //字符串化resp信息
                    ObjectMapper mapper = new ObjectMapper();
                    final String result=mapper.writeValueAsString(ecRes);
                    //发送消息
                    new Thread(){
                            //new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Log.d(this.toString(),"进入socket");
                                        Socket socket = null;
                                        socket = new Socket("219.223.193.99", 10086);
                                        OutputStream dataOutput = socket.getOutputStream();
                                        dataOutput.write(result.getBytes("utf-8"));
                                        dataOutput.flush();
                                        Log.d(this.toString(),"数据:"+result+"已发送到客户端");
                                        socket.shutdownOutput();
                                        //获得返回
                                        //DataInputStream dataInput = new InputStream(socket.getInputStream());从服务器收到的数据
                                        BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                        String line=null;
                                        String info=null;
                                        while ((info=br.readLine())!=null) {
                                            Log.d(this.toString(),"数据:"+info);
                                            line = line + info;
                                        }
                                        Log.d(this.toString(),"接收到来自服务器的数据:"+line+"\n");
                                        dataOutput.close();
                                        br.close();
                                        socket.close();
                                        //button.setText("已初始化，请不要重复点击");
                                        button.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                button.setText("已初始化，请不要重复点击");
                                            }
                                        });
                                    }catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                    //).run();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //查询公钥
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从文件中读出数据
                FileInputStream in = null;
                BufferedReader reader = null;
                StringBuffer content = new StringBuffer();
                try {
                    in = openFileInput("mykeys");
                    reader = new BufferedReader(new InputStreamReader(in));
                    String line = "";
                    while ((line = reader.readLine()) != null)
                        content.append(line);
                    if (in != null)
                        in.close();//注意close的对象
                    textView2.setText(content);
                } catch (FileNotFoundException e) {
                    textView2.setText("无");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        /*
        IniButtonVar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Socket socket = null;
                                    socket = new Socket("219.223.193.99", 8080);
                                    //DataInputStream dataInput = new DataInputStream(socket.getInputStream());//从服务器收到的数据
                                    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                                    out.writeUTF("12345");
                                    Log.d(this.toString(),"数据已发送到客户端");
                                    out.close();
                                    socket.close();
                                    IniStatusVar.setText("已发送");
                                }catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                ).run();

            }

        });
        */


    }
    public static class EcRes{
        public String type;
    }
}

